package net.midnighttd.engine.view.sprite;

import net.midnighttd.engine.view.sprite.Sprite;

import java.util.*;
import java.awt.*;

/**
 * Author: Adam Scarr
 * Date: 24/04/2009
 * Time: 8:36:58 PM
 */
public class SpriteList implements Comparable {
    private LinkedList<Sprite> sprites = new LinkedList<Sprite>();
    private Queue<Sprite> removeQueue = new LinkedList<Sprite>();
    private Queue<Sprite> addQueue = new LinkedList<Sprite>();
    private boolean delayModification = false;

    public synchronized int compareTo(Object o) {
        return sprites.getFirst().compareTo(o);
    }

    public synchronized void drawAll(Graphics g) {
        delayModification = true;
        for(Sprite sprite: sprites) {
            sprite.drawAll(g);
        }
        completeDelayedModifications();
    }

    public synchronized void add(Sprite sprite) {
        if(delayModification) {
            addQueue.add(sprite);
        } else {
            sprites.add(sprite);
        }
    }

    public synchronized void remove(Sprite sprite) {
        if(delayModification) {
            removeQueue.add(sprite);
        } else {
            sprites.remove(sprite);
        }
    }

    public void completeDelayedModifications() {
        Sprite s;

        delayModification = false;

        while((s = addQueue.poll()) != null) {
            add(s);
        }

        while((s = removeQueue.poll()) != null) {
            remove(s);
        }
    }

    public synchronized boolean isEmpty() {
        return sprites.isEmpty();
    }

    public synchronized void updateAll() {
        delayModification = true;
        for(Sprite sprite: sprites) {
            sprite.update();
        }

        completeDelayedModifications();
    }
}